package com.zygame.sdk.service;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.zygame.sdk.model.UserModel;
import com.zygame.sdk.utils.SharedPreferencesHelper;
import com.zygame.sdk.utils.http.HttpUtil;
import com.zygame.sdk.utils.http.NetHttpUtil;
import com.zygame.sdk.utils.log.LogHelper;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

public class HeartbeatService extends Service {
    private Thread mThread;
    public int count = 0;
    private boolean isTip = true;
    private static String mRestMsg;
    private static String KEY_REST_MSG = "KEY_REST_MSG";
    private Context context;
    private boolean isStop = true;
    @SuppressLint("HandlerLeak")
    private  Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            HttpUtil.game_online_time(context, gameline, gameJson, login_token, token);
            LogHelper.i("sss", login_token + " 请求");
        }
    };

    Runnable runnable = new Runnable() {

        @Override
        public void run() {
            while (!isStop) {
                token = SharedPreferencesHelper.getInstance().getToken(context);
                login_token = UserModel.getInstance().getLogin_Token();
                gameJson = SharedPreferencesHelper.getInstance().getGameJson(context);

                LogHelper.i("sss", login_token + " sss");
                if (!TextUtils.isEmpty(token) && null != login_token && !TextUtils.isEmpty(gameJson)) {
                   handler.sendEmptyMessage(0);
                }
                try {
                    Thread.sleep(60 * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

//                handler.getLooper();
//                handler.postDelayed(runnable, 60 * 1000);
            }
        }
    };


    NetHttpUtil.DataCallback gameline = new NetHttpUtil.DataCallback() {
        @Override
        public void callbackSuccess(Object paramObject) {

            LogHelper.i("sss",paramObject.toString()+"在线");

        }

        @Override
        public void callbackError(String error) {
            LogHelper.i("sss","在线失败");
        }
    };
    private String token;
    private String login_token;
    private String gameJson;


    private void sendHeartbeatPackage(String msg) {
//		HttpURLConnection

        HttpGet httpGet = new HttpGet(msg);
        DefaultHttpClient httpClient = new DefaultHttpClient();
        // 发送请求
        HttpResponse httpResponse = null;
        try {
            httpResponse = httpClient.execute(httpGet);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (httpResponse == null) {
            return;
        }

        // 处理返回结果
        final int responseCode = httpResponse.getStatusLine().getStatusCode();
        if (responseCode == HttpStatus.SC_OK) {
            // 只要服务器有回应就OK
            count = 0;
            isTip = true;
        } else {
        }

    }

    @Override
    public void onCreate() {
        super.onCreate();
        context = this;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        isStop = true;
        Log.i("sss","setvice Onde");
    }

    public void onStart(Intent intent, int startId) {
        // 从本地读取服务器的URL，如果没有就用传进来的URL
//		mRestMsg = getRestMsg();
//		if (mRestMsg == null || mRestMsg == "") {
//			mRestMsg = intent.getExtras().getString("url");
//		}
//		setRestMsg(mRestMsg);
        isStop  = false;
        mThread = new Thread(runnable);
        mThread.start();
        super.onStart(intent, startId);
    }


    class OnLineTask extends AsyncTask<String, String, String> {

        @Override
        protected String doInBackground(String... params) {
            String token = SharedPreferencesHelper.getInstance().getToken(context);
            String login_token = UserModel.getInstance().getLogin_Token();
            String gameJson = SharedPreferencesHelper.getInstance().getGameJson(context);

            if (!TextUtils.isEmpty(token) && null != login_token && !TextUtils.isEmpty(gameJson)) {
                HttpUtil.game_online_time(context, gameline, gameJson, login_token, token);
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);


        }
    }

    public String getRestMsg() {
        SharedPreferences prefer = getSharedPreferences("settings.data",
                Context.MODE_PRIVATE);
        LogHelper.i("@qi", "getRestMsg() " + prefer.getString(KEY_REST_MSG, ""));
        return prefer.getString(KEY_REST_MSG, "");
    }

    public void setRestMsg(String restMsg) {
        SharedPreferences prefer = getSharedPreferences("settings.data",
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefer.edit();
        editor.putString(KEY_REST_MSG, restMsg);
        editor.commit();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

}
